import dynamic from 'next/dynamic';
import { useRouter } from 'next/router';
import { useState, ChangeEvent, useEffect } from 'react';
import { Input, Button, message, Select } from 'antd';

import requestInstance from '@/service/fetch';

import '@uiw/react-md-editor/markdown-editor.css';
import '@uiw/react-markdown-preview/markdown.css';
import styles from './new.module.scss'

const MDEditor = dynamic(() => import('@uiw/react-md-editor'), { ssr: false });

const NewEditor = () => {
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('') as any;
  const [allTags, setAllTags] = useState([]);
  const [tagIds, setTagIds] = useState([])
  const { push } = useRouter()

  useEffect(() => {
    getData()
  }, [])

  const getData = async () => {
    const result: any = await requestInstance.get('api/tag/get')
    if (result.code === 200) {
      setAllTags(result.data.allTags || [])
    }
  }

  const handleTitleChange = (event: ChangeEvent<HTMLInputElement>) => {
    setTitle(event?.target?.value);
  };

  const handlePublish = async () => {
    if (!title) {
      message.warning('请输入文章标题')
      return
    }

    const result: any = await requestInstance.post('/api/article/publish', {
      title,
      content,
      tagIds
    })

    if (result?.code === 200) {
      const { id: userId } = result.data.user
      message.success('发布成功')
      userId ? push(`/user/${userId}`) : push('/')
    } else {
      message.error(result?.msg || '发布失败')
    }
  }

  const handleContentChange = (content: any) => {
    setContent(content);
  };

  const handleSelectTag = (value: []) => {
    setTagIds(value);
  }

  return (
    <div className={styles.container}>
      <div className={styles.operation}>
        <Input
          className={styles.title}
          placeholder="请输入文章标题"
          value={title}
          onChange={handleTitleChange}
        />
        <Select
          className={styles.tag}
          mode="multiple"
          allowClear
          placeholder="请选择标签"
          onChange={handleSelectTag}
        >{allTags?.map((tag: any) => (
          <Select.Option key={tag?.id} value={tag?.id}>{tag?.title}</Select.Option>
        ))}</Select>
        <Button
          className={styles.button}
          type="primary"
          onClick={handlePublish}
        >
          发布
        </Button>
      </div>
      <MDEditor value={content} onChange={handleContentChange} height={1080} />
    </div>
  );
};

// 动态控制 layout 显示与否
(NewEditor as any).layout = 'invisible';

export default NewEditor;
